import { parseGIF, decompressFrames } from 'gifuct-js';
import * as PIXI from 'pixi.js';

export default class EarthAnime {
    constructor() {
        this.src = 'https://i.loli.net/2021/05/31/CzfIWDHcgiP7ANB.gif';
        this.init();
    }

    init() {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        // document.body.appendChild(canvas);

        fetch(this.src).then(resp => resp.blob()).then(blob => {
            const {stage} = this.app;
            blob.arrayBuffer().then(buffer => {
                const x = parseGIF(buffer);
                const frames = decompressFrames(x, true);

                //render frame
                const length = frames.length; let index = 0;

                let sprite = '';

                function render() {
                    const {dims, patch} = frames[index];
                    const tempImgData = ctx.createImageData(dims.width, dims.height);
                    canvas.width = dims.width + dims.left;canvas.height = dims.height + dims.height;
                    tempImgData.data.set(patch);
                    // ctx.clearRect(0,0, 1000, 1000);
                    ctx.putImageData(tempImgData, dims.left, dims.top);
                    const imgSource = canvas.toDataURL();
                    // console.log(imgSource)
                    stage.removeChild(sprite);
                    sprite = PIXI.Sprite.from(imgSource);
                    stage.addChild(sprite);
                    index++;
                }

                setInterval( () => {
                    render()
                    if(index >= length) index = 0;
                }, 120);
            });
        })
    }
}
